package com.yanqu.road.dao.impl.servercenter;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDao;
import com.yanqu.road.entity.servercenter.ForbiddenInfo;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

public class ForbiddenDaoImpl extends TempDao {

	public boolean addForbiddenInfo(ForbiddenInfo forbiddenInfo) {
		PreparedStatement call = null;
		String sql = "INSERT INTO t_u_forbidden(forbiddenContent ,forbiddenType) VALUES(?,?)";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareStatement(sql);
			int i = 1;
			call.setString(i++, forbiddenInfo.getForbiddenContent());
			call.setInt(i++, forbiddenInfo.getForbiddenType());
			return call.executeUpdate() > 0;
		} catch (Exception e) {
			logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
		} finally {
			getDb().closeConnection(call, null);
		}
		return false;
	}

	public boolean deleteForbiddenInfo(ForbiddenInfo forbiddenInfo) {
		PreparedStatement call = null;
		String sql = "DELETE FROM t_u_forbidden WHERE forbiddenContent=? and forbiddenType=?";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareStatement(sql);
			int i = 1;
			call.setString(i++, forbiddenInfo.getForbiddenContent());
			call.setInt(i++, forbiddenInfo.getForbiddenType());
			return call.executeUpdate() > 0;
		} catch (Exception e) {
			logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
		} finally {
			getDb().closeConnection(call, null);
		}
		return false;
	}

	public void getAll(List<String> forbiddenIp, List<String> forbiddenMac, List<String> forbiddenSpeakIp, List<String> forbiddenSpeakMac) {
		ResultSet rs = null;
		CallableStatement call = null;
		String sql = "SELECT * FROM t_u_forbidden";
		try {
			getDb().setConnName(DbNameStrategy.getUserDb());
			call = getDb().getConnection().prepareCall(sql);
			rs = call.executeQuery();
			while (rs.next()) {
				int forbiddenType = rs.getInt("forbiddenType");
				if (forbiddenType == 1) {
					forbiddenIp.add(rs.getString("forbiddenContent"));
				} else if (forbiddenType == 2) {
					forbiddenMac.add(rs.getString("forbiddenContent"));
				} else if (forbiddenType == 3) {
					forbiddenSpeakIp.add(rs.getString("forbiddenContent"));
				} else if (forbiddenType == 4) {
					forbiddenSpeakMac.add(rs.getString("forbiddenContent"));
				}
			}
		} catch (Exception e) {
			logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
		} finally {
			getDb().closeConnection(call, rs);
		}
	}
}
